package com.dk.controller;

import com.dk.enums.ResultEnum;
import com.dk.pojo.TbUser;
import com.dk.result.Result;
import com.dk.service.TbUserService;
import com.dk.shiro.ShiroUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("userRegister")
@RefreshScope      //自动刷新配置, nacos的
@Api
@ApiOperation("用户注册")
public class TbUserRegisterController {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TbUserService userService;

    //获取短信验证码
    @PostMapping("sendPhoneMessage")
    @ApiOperation(value = "获取短信验证码")
    @ApiImplicitParam(name="phone",value = "手机号",required = true, paramType = "query")
    public Result sendPhoneMessage(@RequestParam String phone){
        try {
            rocketMQTemplate.convertAndSend("phone",phone);
            return Result.OK();
        }catch (Exception e){
            e.printStackTrace();
            return Result.ER();
        }
    }
    //注册
    @PostMapping("register")
    @ApiOperation(value = "注册")
    @ApiImplicitParams({
            @ApiImplicitParam(name="user",value = "用户", paramType = "query"),
            @ApiImplicitParam(name="phoneMessage",value = "手机验证码", paramType = "query")
    })
    public Result register(@RequestParam TbUser user,@RequestParam String phoneMessage){   //phoneMessage是前台传过来的短信验证码
        //1.先判断该用户是否已经注册
        TbUser tbUser = userService.selectByUsername(user.getUsername());
        if(tbUser != null){
            return Result.respones(ResultEnum.FETCH_USERINFO);
        }
        //2.从redis中取出验证码,判断是否正确(一致)
        String o = (String) redisTemplate.opsForValue().get(user.getPhone());
        if(o.equals(phoneMessage)){
            //一致-> 去加密
            String salt = ShiroUtils.generateSalt(6);
            String pwd = ShiroUtils.encryptPassword("MD5", user.getPassword(), salt, 3);
            user.setPassword(pwd);
            user.setSalt(salt);
            userService.addUser(user);
            return Result.OK();

        }else{
            return Result.respones(ResultEnum.CODE_ER);
        }
    }
}
